import {URL_HASH_PREFIX} from "~utils/constants";
import {composeHighlightFromViewstate} from "~manager/viewstateManager";
import loadHighlightText from "~api/highlightText/load";
import {fetch as fetchFromStorage} from "~storage/store";
import loadPage from "~api/highlightPage/load";
import loadImage from "~api/highlightImage/load";
// import {composeHighlightFromViewstate} from "~contents/manager/viewstateManager";
// import loadHighlightText from "~contents/api/highlightText/load";

function loadAll() {
  async function loadAllHighlightsOnPage() {
    if (window.top !== window.self) return; // JM：iframe调用检查
    /* e.g.
    location = https://www.zhihu.com/question/404193511/answer/2395258614#~:~highlights=4efec37a-c8ec-4ed9-864b-70ed10a90276;;国王说可我只能养得起一个啊，-,要不这么着，朕给,-你们出个题吧。给你们仨一人一个金币，你们去买东西，谁拿这一个金币买的东西，能填满旁边内个;;*ver_simple*;;1
    location = https://www.zhihu.com/question/404193511/answer/2395258614#~:~hint=正则表达式符号大全&~:~highlights=4efec37a-c8ec-4ed9-864b-70ed10a90276;;国王说可我只能养得起一个啊，-,要不这么着，朕给,-你们出个题吧。给你们仨一人一个金币，你们去买东西，谁拿这一个金币买的东西，能填满旁边内个;;*ver_simple*;;1
     */
    // const url = location.hostname + location.pathname;
    const url = location.href;
    if (location.hash.indexOf(URL_HASH_PREFIX) !== -1){
      let locationHash = location.hash.match(new RegExp(`${URL_HASH_PREFIX}(.*?)(#|$)`))[1];
      // JM：读进来的location都是encoded，除了定位和展示外，其余地方都用encoded表示
      if (locationHash.startsWith("#")){
        locationHash = locationHash.substring(1, locationHash.length);
      }
      if (locationHash) {
        // getHighlightsFromUrl(url, locationHash);
        console.log("load highlights from url...");
        let viewstates = locationHash.split("__").filter(value => { return value.trim() !== "" });
        const highlights = [];
        viewstates.forEach((viewstate) => {
          highlights.push(composeHighlightFromViewstate(viewstate));
        });
        loadHighlights(highlights);
      }
    } else {
      const viewstates = await fetchFromStorage(url);
      const highlights = [];
      if (viewstates) {
        viewstates.forEach((viewstate) => {
          highlights.push(composeHighlightFromViewstate(viewstate));
        });
        loadHighlights(highlights);
      }
    }
  }

  function loadHighlights(highlights) {
    if (!highlights) return;

    for (let i = 0; i < highlights.length; i++) {
      if (highlights[i].ver === "*ver_image*") {
        loadImage(highlights[i], highlights[i].uuid);
      } else if (highlights[i].ver === "*ver_page*") {
        loadPage(highlights[i], highlights[i].uuid);
      } else {
        loadHighlightText(highlights[i], highlights[i].uuid);
        // loadBlock(highlights[i], highlights[i].uuid);
      }
    }
  }

  if (document.readyState === 'loading') {
    document.removeEventListener('DOMContentLoaded', loadAllHighlightsOnPage); // Prevent duplicates
    document.addEventListener('DOMContentLoaded', loadAllHighlightsOnPage);
  } else {
    // Run immediately if the page is already loaded
    loadAllHighlightsOnPage();
  }
}

export default loadAll;
